package com.bdqn.mzc.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SING="fds*kgj4#$!%#5f4d@";

    /**
     * 生成 token   hander.payload.sing 三部分组成.
     */
    public static String getToken(Map<String,String> map){
        Calendar instance=Calendar.getInstance();
        //默认3天过期
        instance.add(Calendar.DATE,3);
        //创建jwt builder
        JWTCreator.Builder builder= JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //指定令牌过期时间
        builder.withExpiresAt(instance.getTime());
        //sing
        String token = builder.sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token 合法性
     * @param token
     */
    public static DecodedJWT verify(String token){
        return  JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 获取token中的id
     * @param request
     * @return
     */
    public static Integer getUserId(HttpServletRequest request){
        String token=request.getHeader("token");
        DecodedJWT verify= JWTUtils.verify(token);
        String id = verify.getClaim("userId").asString();
        Integer newId=Integer.valueOf(id);
        return newId;
    }



}
